package middlewares

import (
	_ "minititok/Entities"
	"minititok/Services"
	"minititok/utils"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

var skipPaths = map[string]struct{}{
	"/login/":    {},
	"/register/": {},
	"/refresh/":  {},
}

func JWTAuthMiddleware(jwtManager *utils.JWTManager) gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.URL.Path
		// 过滤登录接口，允许不带token访问
		if _, ok := skipPaths[path]; ok {
			c.Next()
			return
		}

		if strings.HasPrefix(path, "/reVideo/") ||
			strings.HasPrefix(path, "/getCover/") ||
			strings.HasPrefix(path, "/getAvatar/") {
			c.Next()
			return
		}

		authHeader := c.GetHeader("Authorization")
		if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
			c.Abort()
			return
		}

		tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
		claims, err := jwtManager.VerifyToken(tokenStr)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
			c.Abort()
			return
		}
		// 读取用户uuid，加载用户（假设是UID）
		uuid, ok := claims["uuid"].(string)
		if !ok {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Token中不包含UUID"})
			c.Abort()
			return
		}
		intUUID, err := strconv.Atoi(uuid)

		user, err := Services.FindUserByUID(intUUID)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
			c.Abort()
			return
		}

		// 把用户信息放进context，后续handler可用
		c.Set("user", user)
		c.Next()
	}
}
